package com.xj.driver.mqtt.subscriber.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.common.bean.constant.Common;
import com.xj.driver.mqtt.service.UpBizService;
import com.xj.driver.mqtt.subscriber.domain.StationSwitchManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

/**
 * MQTT消息处理器
 */
@Slf4j
public class MqttMessageProcessor {

    private final UpBizService upBizService;
    private final StationSwitchManager stationSwitchManager;

    public MqttMessageProcessor(UpBizService upBizService, StationSwitchManager stationSwitchManager) {
        this.upBizService = upBizService;
        this.stationSwitchManager = stationSwitchManager;
    }

    /**
     * 处理MQTT消息
     */
    public void processMessage(Message<?> message) {
        log.info("设备信息: {}", message);

        String payload = (String) message.getPayload();
        MessageHeaders headers = message.getHeaders();

        String mqttReceivedTopic = headers.get("mqtt_receivedTopic", String.class);

        // 解析主题和消息内容
        TopicInfo topicInfo = parseTopic(mqttReceivedTopic);
        if (!topicInfo.isValid()) {
            return;
        }

        JSONObject jsonObject = JSON.parseObject(payload);
        JSONArray deviceArray = jsonObject.getJSONArray("devices");

        String stationNo = extractStationNoFromTopic(topicInfo.getStationPart());

        // 根据命令类型处理消息
        handleMessageByCommand(topicInfo.getCommand(), stationNo, deviceArray);
    }

    /**
     * 根据命令类型处理消息
     */
    private void handleMessageByCommand(String command, String stationNo, JSONArray deviceArray) {
        switch (command) {
            case Common.Driver.Type.UP_BIZ:
                handleUpBiz(stationNo, deviceArray);
                break;
            case Common.Driver.Type.HEART_BEAT:
                handleHeartbeat(stationNo);
                break;
            default:
                log.info("暂不支持的主题操作: {}", command);
        }
    }

    /**
     * 处理业务消息
     */
    private void handleUpBiz(String stationNo, JSONArray payload) {
        String cleanStationNo = cleanStationNo(stationNo);

        // 只处理当前活跃设备的业务消息
        if (cleanStationNo.equals(stationSwitchManager.getActiveStationNo())) {
            log.info("处理活跃设备[{}]的业务消息: {}", cleanStationNo, payload);
            upBizService.doUpBiz(payload);
        } else {
            log.debug("忽略非活跃设备[{}]的业务消息", cleanStationNo);
        }
    }

    /**
     * 处理心跳消息
     */
    private void handleHeartbeat(String stationNo) {
        stationSwitchManager.updateHeartbeat(cleanStationNo(stationNo));
        stationSwitchManager.checkAndSwitch();
    }

    /**
     * 解析主题信息
     */
    private TopicInfo parseTopic(String topic) {
        String[] topicParts = topic.split("/");
        if (topicParts.length < 4) {
            log.warn("主题格式错误: {}", topic);
            return TopicInfo.invalid();
        }

        String command = topicParts[3];
        String stationPart = topicParts.length > 4 ? topicParts[4] : "";

        return new TopicInfo(command, stationPart, true);
    }

    /**
     * 从主题中提取设备编号
     */
    private String extractStationNoFromTopic(String stationPart) {
        return stationPart.split(":")[0];
    }

    /**
     * 清理设备编号
     */
    private String cleanStationNo(String stationNo) {
        return stationNo.contains(":") ? stationNo.split(":")[0] : stationNo;
    }

    /**
     * 主题信息封装类
     */
    @lombok.Data
    @lombok.AllArgsConstructor
    private static class TopicInfo {
        private String command;
        private String stationPart;
        private boolean valid;

        public static TopicInfo invalid() {
            return new TopicInfo("", "", false);
        }
    }
}